package com.timoon.component.panel.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.wicket.markup.html.panel.FeedbackPanel;

/**
 * 验证数据
 * @author Administrator
 *
 */
public class ValidatorFeedbackPanel extends FeedbackPanel{
	private static final long serialVersionUID = 1388425290002419056L;

	private Map<String,Object> data;
	
	private boolean istested=true;
	
	public ValidatorFeedbackPanel(String id,Map<String,Object> data) {
		super(id);
		// TODO Auto-generated constructor stub
		
		this.data=data;
		
		this.setOutputMarkupId(true);
	}
	public boolean assertNotNull(String key,String field,String expression){
		Object value=null;
		if(expression!=null){
			value=this.getValueByExpression(key, expression);
		}else{
			value=data.get(key);
		}
		
		if(value==null){
			this.istested=false;
			this.error("字段"+field+"不能为空");
			return false;
		}
		return true;
	}
	public boolean assertNumber(String key,String field,String expression){
		
		Object value=null;
		if(expression!=null){
			value=this.getValueByExpression(key, expression);
		}else{
			value=data.get(key);
		}
		
		try{
			Integer.valueOf(value.toString());
		}catch(Exception e){
			this.istested=false;
			this.error("字段"+field+"必须为数字");
			return false;
		}
		return true;
	}
	public boolean isTested(){
		Boolean result=new Boolean(this.istested);
		this.istested=true;
		return result;
	}
	public void setData(Map<String, Object> data) {
		this.data = data;
	}
	private String getValueByExpression(String key,String expression){
		String value=null;
		Object obj=data.get(key);
		try {
			value=BeanUtils.getProperty(obj, expression);
		} catch (IllegalAccessException | InvocationTargetException
				| NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}
}
